<?php
/**
 * desc 生成授权code r=oauth2/authroize&response_type=code&client_id=testclient&state=xyz
 * User: wangshuai
 * Date: 2021/9/6
 * Time: 15:27
 * Email: <1076890579@qq.com>
 */
$dsn= 'mysql:dbname=oauth;host=localhost';
$username = 'root';
$password = '12345678';
// 错误报告（这毕竟是一个演示！）
ini_set('display_errors',1);
error_reporting(E_ALL);

// 自动加载
require_once('./src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

// 通过存储对象或对象数组存储的oauth2服务器类
$server = new OAuth2\Server($storage);

// 授权码 有效期只有30秒
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));

// 客户端证书
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));

// 用户凭据
$server->addGrantType(new OAuth2\GrantType\UserCredentials($storage));
// 刷新令牌  启用这个会报错，原因未知
// $server->addGrantType(new OAuth2\GrantType\RefreshToken($refreshStorage))
$request = OAuth2\Request::createFromGlobals();
$response = new OAuth2\Response();

// validate the authorize request
if (!$server->validateAuthorizeRequest($request, $response)) {
    die;
}
// display an authorization form
if (empty($_POST)) {
    exit('
        <form method="post">
          <label>Do You Authorize TestClient?</label><br />
          <input type="submit" name="authorized" value="yes">
          <input type="submit" name="authorized" value="no">
        </form>');
}

// print the authorization code if the user has authorized your client
$is_authorized = ($_POST['authorized'] === 'yes');
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {
    // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
    $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
    exit("SUCCESS! Authorization Code: $code");
}
$response->send();